<template>
  <div class="category-edit">
    <!-- 默认页面 - 当没有ID参数时显示 -->
    <div v-if="!hasId" class="default-page">
      <el-card class="welcome-card" shadow="hover">
        <div class="welcome-content">
          <el-icon class="welcome-icon" size="80" color="#409eff">
            <Edit />
          </el-icon>
          <h2>分类编辑功能</h2>
          <p>欢迎使用分类编辑功能</p>
          <div class="feature-list">
            <div class="feature-item">
              <el-icon><Document /></el-icon>
              <span>编辑分类基本信息</span>
            </div>
            <div class="feature-item">
              <el-icon><Tools /></el-icon>
              <span>更新分类状态</span>
            </div>
            <div class="feature-item">
              <el-icon><Folder /></el-icon>
              <span>管理分类层级</span>
            </div>
            <div class="feature-item">
              <el-icon><Setting /></el-icon>
              <span>配置分类属性</span>
            </div>
          </div>
          <div class="action-buttons">
            <el-button type="primary" @click="goToCategoryList">
              <el-icon><List /></el-icon>
              查看分类列表
            </el-button>
            <el-button @click="goToAddCategory">
              <el-icon><Plus /></el-icon>
              添加新分类
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 编辑表单页面 - 当有ID参数时显示 -->
    <el-card v-else class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>编辑分类</span>
          <div class="header-actions">
            <el-button @click="handleBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="category-form"
        v-loading="loading"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入分类名称" 
            maxlength="50" 
            show-word-limit 
          />
        </el-form-item>
        
        <el-form-item label="分类编码" prop="code">
          <el-input 
            v-model="form.code" 
            placeholder="请输入分类编码" 
            maxlength="20"
            :disabled="form.id"
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入分类描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            保存
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Document, Tools, Folder, Setting, List, Plus } from '@element-plus/icons-vue'
import { categoryApi } from '@/api'

const router = useRouter()
const route = useRoute()

// 判断是否有ID参数
const hasId = computed(() => {
  return !!route.params.id
})

// 表单数据
const form = reactive({
  id: null,
  name: '',
  code: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9_]+$/, message: '编码只能包含大写字母、数字和下划线', trigger: 'blur' }
  ]
}

// 状态
const loading = ref(false)
const submitting = ref(false)
const formRef = ref()

// 获取分类详情
const getCategoryDetail = async (id: string) => {
  loading.value = true
  try {
    const res: any = await categoryApi.getDetail(parseInt(id))
    Object.assign(form, res)
  } catch (error) {
    ElMessage.error('获取分类详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    await categoryApi.update(form.id!, {
      ...form,
      status: 1
    })
    ElMessage.success('保存成功')
    router.push('/category/list')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消编辑吗？未保存的内容将丢失。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    )
    router.back()
  } catch {
    // 用户选择继续编辑
  }
}

// 返回
const handleBack = () => {
  router.back()
}

// 重置表单
const handleReset = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置表单吗？所有修改将丢失。',
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (formRef.value) {
      formRef.value.resetFields()
    }
    ElMessage.success('表单已重置')
  } catch {
    // 用户取消
  }
}

// 跳转到分类列表
const goToCategoryList = () => {
  router.push('/category/list')
}

// 跳转到添加分类
const goToAddCategory = () => {
  router.push('/category/add')
}

onMounted(() => {
  const id = route.params.id as string
  if (id) {
    getCategoryDetail(id)
  }
})
</script>

<style scoped>
.category-edit {
  padding: 20px;
}

.default-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.welcome-card {
  max-width: 600px;
  width: 100%;
}

.welcome-content {
  text-align: center;
  padding: 40px 20px;
}

.welcome-icon {
  margin-bottom: 20px;
}

.welcome-content h2 {
  color: #303133;
  margin-bottom: 10px;
  font-size: 24px;
}

.welcome-content p {
  color: #606266;
  margin-bottom: 30px;
  font-size: 16px;
}

.feature-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  color: #606266;
}

.feature-item .el-icon {
  color: #409eff;
  font-size: 20px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.category-form {
  max-width: 600px;
  margin: 0 auto;
}

.form-actions {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .category-edit {
    padding: 10px;
  }
  
  .feature-list {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .form-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
}
</style> 